import { useEffect } from "react";
import { Outlet, useLocation, useNavigate } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { NavBar, Toast } from "antd-mobile";
import styles from "./App.module.less";
import { createAction } from "@common/utils";
import {
  POP_PAGE_STACK,
  SET_PAGE_STACK,
  SET_ERR_MSG,
} from "@store/global-state/action-types";

const App = () => {
  const location = useLocation();
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const pageStack = useSelector((state) => state.globalState.pageStack);
  const pageTitle = useSelector((state) => state.globalState.pageTitle);
  const showHomeBtn = useSelector((state) => state.globalState.showHomeBtn);
  const errMsg = useSelector((state) => state.globalState.errMsg);

  useEffect(() => {
    window.scrollTo(0, 0);
    if ("cordova" in window) {
      if (!window.sessionStorage.getItem("token")) {
        navigate("/");
      }
    }
  }, [location]);

  useEffect(() => {
    if (errMsg) {
      Toast.show({
        icon: "fail",
        content: errMsg,
        duration: 3000,
        afterClose: () => dispatch(createAction(SET_ERR_MSG, null)),
      });
    }
  }, [errMsg]);

  const handleBack = () => {
    let path = pageStack[pageStack.length - 2];
    navigate(path);
    dispatch(createAction(POP_PAGE_STACK));
  };

  const HomeBtn = () => {
    if (pageStack.length > 1 && showHomeBtn) {
      return (
        <i
          className="iconfont icon-shouye"
          style={{ fontSize: "1.25rem" }}
          onClick={() => {
            navigate(pageStack[0]);
            dispatch(createAction(SET_PAGE_STACK, [pageStack[0]]));
          }}
        />
      );
    } else {
      return null;
    }
  };

  return (
    <div className={styles.app}>
      <div className={styles.top}>
        <NavBar
          backArrow={pageStack.length > 1}
          onBack={handleBack}
          right={<HomeBtn />}
        >
          {pageTitle}
        </NavBar>
      </div>
      <Outlet />
    </div>
  );
};

export default App;
